<template>

    <input type="file" ref="fileRef" id="file" @change="filePathChange" />
    <el-button type="primary" size="mini" @click="uploadFile"
    >确认上传</el-button
    >
    <div class="img-show">
      <img v-if="data.src" :src="data.src"/>
    </div>

</template>

<script>
import {saveOnIpfs} from "../../api/etherneum/api";
import {ElMessage} from "element-plus";
import {reactive} from "vue";


export default {
  name: "UploadPic",
  emits:["getUploadHash"],
  setup(props,{emit}){
    const data=reactive({
      uploadFileHash:'',
      uploadFileName:'',
      fileBlob:'',
      src:''
    })
    const filePathChange = () => {
      let res = document.getElementById("file");
      const reader=new FileReader()
      reader.readAsArrayBuffer(res.files[0])
      data.fileReady = false;

      reader.onload = (e) => {
        data.fileBlob = e.target.result;
        console.log('fileBlob:',data.fileBlob)
        let binaryData = [];
        binaryData.push(data.fileBlob);
        data.src= window.URL.createObjectURL(new Blob(binaryData))
        data.fileReady = true;

      };
    }
    const uploadFile = async () => {
      if (!data.fileBlob){
        ElMessage.error('未选择文件')
        return
      }
      console.log("start Upload");
      data.uploadFileHash = await saveOnIpfs(data.fileBlob, (hash) => {
        data.uploadFileHash = hash;
        emit('getUploadHash',hash)
        ElMessage.success("上传成功，cid=" + hash);
      });
    };
    return{
      data,
      uploadFile,
      filePathChange
    }
  }
}
</script>

<style lang="scss" scoped>
.img-show{
  img{
    width: 200px;
  }

}
</style>